package com.ow.dva.module.version.app;

import com.ow.dva.module.base.entity.json.RT;
import com.ow.dva.module.version.entity.Version;
import com.ow.dva.module.version.service.VersionService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 版本控制管理 客户端 Controller
 * @author GaoXiang
 * @version 1.0
 */
@Controller
@RequestMapping("/app/version")
public class AppVersionController {

    /**
     * 下载新版本
     * @param version 新版本
     * @return 文件流
     */
    @RequestMapping(value="/downOne")
    @ResponseBody
    public void down(HttpServletResponse response, HttpServletRequest request, Version version)  {

        try {
            version.setType(1);
            version=versionService.getNewVersion(version);
            String fileName="huiruo_"+version.getName()+".apk";
            response.setContentType(request.getServletContext().getMimeType(fileName));
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            findAPK(response, request, version);
        } catch (Exception e) {
//            e.printStackTrace();
        }

    }

    private void findAPK(HttpServletResponse response, HttpServletRequest request, Version version) throws IOException {
        if(!"".equals(version.getUrl())){
            String path = request.getSession().getServletContext().getRealPath(version.getUrl());
            File file  = new File(path);
            //如果文件存在
            if(file.exists()){
                InputStream in = new FileInputStream(file);
                outputStream(response,in,request);
            }
        }
    }

    /**
     * 检测新版本接口
     * @param version 版本
     * @return 新版本
     */
    @RequestMapping(value="/checkOne")
    @ResponseBody
    public RT check(Version version){
        version.setType(1);
        version=versionService.getNewVersion(version);
        return RT.ok(version);
    }

    /**
     * 输出文件流
     * @param response
     * @param in
     * @throws IOException
     */
    public void outputStream(HttpServletResponse response, InputStream in, HttpServletRequest request) throws IOException {
        OutputStream os = response.getOutputStream();
        int b;
        while((b=in.read()) != -1) {
            os.write(b);
        }
        in.close();
        os.flush();
        os.close();
    }

    //---------------------------- property -------------------------------

    @Resource
    private VersionService versionService;

}
